package com.woniu.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.woniu.been.entity.Courses;
import com.woniu.mapper.CourseChaptersMapper;
import com.woniu.mapper.CourseMapper;
import com.woniu.service.CoursesService;

@Service
public class CoursesServiceImpl implements CoursesService {
    @Autowired
    private CourseMapper mapper;

    @Autowired
    private CourseChaptersMapper courseChaptersMapper;

    @Override
    public List<Courses> getCoursesByCategoryId(Integer categoryId) {
        System.out.println("=== 开始查询课程 ===");
        System.out.println("传入的categoryId: " + categoryId);
        System.out.println("categoryId类型: " + (categoryId != null ? categoryId.getClass().getName() : "null"));
        
        List<Courses> courses = mapper.findCoursesByCategoryId(categoryId);
        
        System.out.println("查询结果数量: " + (courses != null ? courses.size() : "null"));
        System.out.println("查询结果: " + courses);
        System.out.println("=== 查询课程结束 ===");
        
        return courses;
    }

    @Override
    public void addCourse(Courses course) {
        mapper.insertCourse(course);
    }

    @Override
    @Transactional
    public void addCourse(Courses course, Integer chapterId) {
        // 先插入课程
        mapper.insertCourse(course);
        
        // 再插入章节与课程的关联关系
        if (course.getCourseId() != null && chapterId != null) {
            courseChaptersMapper.insertRelation(chapterId, course.getCourseId().intValue());
            System.out.println("课程插入成功，课程ID: " + course.getCourseId());
            System.out.println("章节ID: " + chapterId);
            System.out.println("章节与课程关联关系建立成功");
        }
    }

    @Override
    public void updateCourse(Courses course) {
        mapper.updateCourse(course);
    }

    @Override
    public void deleteCourse(Long id) {
        mapper.deleteCourse(id);
    }

    @Override
    public List<Courses> getCoursesByCategoryName(String categoryName) {
        return mapper.findCoursesByCategoryName(categoryName);
    }

    @Override
    public Courses getCourseById(Long courseId) {
        return mapper.findCourseById(courseId);
    }

    @Override
    public List<Courses> getCoursesByChapterId(Integer chapterId) {
        return mapper.findCoursesByChapterId(chapterId);
    }
}